
#import "NexusHttpRequest.h"

@implementation NexusHttpRequest

//
// nexus php
//
@synthesize cookieNexusPhp													= _cookieNexusPhp;

//
// language
//
@synthesize cookieLanguage													= _cookieLanguage;

//
// php session id
//
@synthesize cookiePHPSessionId												= _cookiePHPSessionId;

//
// parse
//
@synthesize xmlParser														= _xmlParser;

//
// init
//
- (id)init
{
	//
	// call super
	//
	self																	= [super init];
	if(!self)
		return nil;
	
	//
	// setup default values
	//
	self.cookieLanguage														= @"en";
	
	return self;
}

//
// dealloc
//
- (void)dealloc
{
	self.cookieNexusPhp														= nil;
	self.cookieLanguage														= nil;
	self.cookiePHPSessionId													= nil;
	self.xmlParser															= nil;
	
	[super dealloc];
}

//
// set header with cookie
//
- (void)setHeaderWithCookie
{
	NSDate* expires															= [NSDate dateWithTimeIntervalSinceNow:0x7fffffff];
	NSMutableArray* cookies													= [NSMutableArray arrayWithCapacity:6];
	[cookies addObject:[self cookieWithName:@"c_lang_folder" value:self.cookieLanguage expires:expires]];
	if(self.cookieNexusPhp.length)
		[cookies addObject:[self cookieWithName:@"nexusphp_u2" value:self.cookieNexusPhp expires:expires]];
	if(self.cookiePHPSessionId.length)
		[cookies addObject:[self cookieWithName:@"PHPSESSID" value:self.cookiePHPSessionId expires:expires]];
	[self.request setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:cookies]];
}

//
// setup request
//
- (void)setupRequest
{
	//
	// call super
	//
	[super setupRequest];
	
	//
	// setup cookie
	//
	[self setHeaderWithCookie];
}

//
// finished
//
- (void)connectionDidFinishLoading:(NSURLConnection*)connection
{
	//
	// process cookie
	//
	if(!self.cookieNexusPhp.length)
	{
		NSArray* cookies													= [NSHTTPCookie cookiesWithResponseHeaderFields:[self.response allHeaderFields] forURL:[self.request URL]];
		for(NSHTTPCookie* cookie in cookies)
		{
			if([cookie.name isEqualToString:@"nexusphp_u2"])
				self.cookieNexusPhp											= cookie.value;
			else if([cookie.name isEqualToString:@"PHPSESSID"])
				self.cookiePHPSessionId										= cookie.value;
		}
	}
	
	//
	// call super
	//
	[super connectionDidFinishLoading:connection];
}

@end
